const router = require('koa-router')()
const jwt = require('jsonwebtoken');

const User = require('../model/user')

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Topik!'
  })

  ctx.response.redirect('/topikList')
})

router.get('/login', async (ctx, next) => {
  ctx.cookies.set(
    'Authorization', '', {
      maxAge: 0
    }
  );

  await ctx.render('user/login', {
    type: '登陆',
    username: 'kree',
    password: '123456'
  });
})

router.get('/register', async (ctx, next) => {
  await ctx.render('user/login', {
    type: '注册'
  });
})

router.post('/login', async (ctx, next) => {
  //console.log(ctx.params, ctx.query, ctx.request.body);

  var msg, data;
  var { username, password } = ctx.request.body

  if (password && username) {

    var crypto = require('crypto');
    var md5 = crypto.createHash('md5');
    md5.update(password);
    var sign = md5.digest('hex');

    data = await User.findOne({
      username: username,
      password: sign
    })

    if (!data) {
      msg = '错误的用户名或密码'
    } else {
      let token = jwt.sign({ id: data._id }, 'shared-topik')

      ctx.cookies.set(
        'Authorization', token, {
          maxAge: 7200000
        }
      );
    }
  } else {
    msg = '无效数据'
  }

  ctx.body = {
    msg: msg,
    data: data
  }
})

router.post('/register', async (ctx, next) => {
  var msg, data;
  var { username, password, repassword } = ctx.request.body

  if (username && password && password === repassword) {

    let one = await User.findOne({
      username: username
    })

    if (!one) {
      var crypto = require('crypto');
      var md5 = crypto.createHash('md5');
      md5.update(password);
      var sign = md5.digest('hex');

      data = await new User({
        username: username,
        password: sign
      }).save()
    } else {
      msg = '已存在的用户名'
    }

    ctx.body = {
      msg: msg,
      data: data
    }
  }
})

router.get('/loginout', async (ctx, next) => {
  ctx.cookies.set(
    'Authorization', '', {
      maxAge: 0
    }
  );

  ctx.response.redirect('/login')
})


module.exports = router
